#include "fbtransferserver.h"
#include "fbtransferthread.h"
#include "NetworkCommonFunction.h"

#include <QDebug>
extern "C"
{
#include <winsock2.h>
}


FBTransferServer* FBTransferServer::createServerThread()
{
	static FBTransferServer* transferServer = new FBTransferServer;
	transferServer->start();
	return transferServer;
}

FBTransferServer::FBTransferServer()
{
}


void FBTransferServer::run()
{
	int ret;
	int serverSocket = ::socket(AF_INET, SOCK_STREAM, 0);
	if(serverSocket == INVALID_SOCKET)
	{
		qDebug()<<"Create file browser transfer server socket error";
		emit errorHappend(WSAGetLastError());
		return;
	}

	int reuseAddr = 1;
	ret = ::setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&reuseAddr, sizeof(reuseAddr));
	if(ret == SOCKET_ERROR)
	{
		qDebug()<<"Set file browser server socket reuse address error";
	}

	sockaddr_in bindAddress;
	bindAddress.sin_family = AF_INET;
	bindAddress.sin_addr.s_addr = INADDR_ANY;
	bindAddress.sin_port = htons( FBTransferServerPort );

	ret = ::bind(serverSocket, (SA*)&bindAddress, sizeof(bindAddress));
	if(ret == SOCKET_ERROR)
	{
		qDebug()<<"Bind file browser server socket error";
		emit errorHappend(WSAGetLastError());
		return;
	}

	ret = ::listen(serverSocket, SOMAXCONN);
	if(ret == SOCKET_ERROR)
	{
		qDebug()<<"Listen file browser server socket error";
		emit errorHappend(WSAGetLastError());
		return;
	}

	sockaddr_in clientAddress;
	int clientAddrLen = sizeof(clientAddress);
	while(true)
	{
		int clientSocket = ::accept(serverSocket, (SA*)&clientAddress, &clientAddrLen);
		if(clientSocket == INVALID_SOCKET)
		{
			qDebug()<<"Accept file browser server socket error";
			continue;
		}

		FBTransferThread* transferThread = new FBTransferThread(clientSocket);
		connect(transferThread, SIGNAL(terminated()),
				this, SLOT(deleteLater()));
		transferThread->start();
	}
}
